package de.fuberlin.inf.alp2.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This class is intended to simplify requesting user input.
 * @author stefanr
 *
 */
public class ConsoleInput {
	
	/**
	 * This method helps reading in int values.
	 * @param message The text to demand an input of an integer by the user.
	 * @param errorMessage An error message if the conversion of the entered
	 * text failed.
	 * @return The entered number as int.
	 */
	public static int readInt(String message, String errorMessage) {
		while (true) {
			try {
				return Integer.parseInt(ConsoleInput.readString(message));
			}
			catch (NumberFormatException exc) {
				System.out.println(errorMessage);
			}
		}
	}
	
	/**
	 * This method helps reading in double values.
	 * @param message The text to demand an input of an double by the user.
	 * @param errorMessage An error message if the conversion of the entered
	 * text failed.
	 * @return The entered value as double.
	 */
	public static double readDouble(String message, String errorMessage) {
		while (true) {
			try {
				return Double.parseDouble(ConsoleInput.readString(message));
			}
			catch (NumberFormatException exc) {
				System.out.println(errorMessage);
			}
		}
	}
	
	/**
	 * This method helps reading in strings.
	 * @param message The text to demand an input of an integer by the user.
	 * @return The entered text as string.
	 */

	public static String readString(String message) {
		String inputString = "";
		BufferedReader console = new BufferedReader(
				new InputStreamReader(System.in) );

		System.out.print(message + "\n> ");
		try {
			inputString = console.readLine();
		}
		catch (IOException exc) {
			exc.printStackTrace();
		}
		return inputString;
	}
}
